<?php
if (!isset($_SESSION)) {
  session_start();
}
//付款處理頁面
include("common.inc.php");
checklogin();//檢查是否登錄
/**
 * 檢查表單是否被重複提交
 * 相同內容的表單在設定時間內只能提交1次
 * @param int $iTimeOffset
 * @return bool
 */
function checkFormSubmit($iTimeOffset=10){
    // 取得表單的標識
    $idForm = md5(serialize($_POST));
    // 是否需要表單提交檢察
    $iFormCheck = true;
    if (isset($_SESSION['formSubmitCheck'])){
        // 刪除過期的表單標識
        foreach (array_keys($_SESSION['formSubmitCheck']) as $val){
            if (time() > $val){
                unset($_SESSION['formSubmitCheck'][$val]);
            }
        }
    }else {
        $_SESSION['formSubmitCheck'] = array();
        $iFormCheck = false;
    }
    if ($iFormCheck == true){
        // 檢查是否有重複標識的提交記錄
        foreach ($_SESSION['formSubmitCheck'] as $val){
            if ($val == $idForm){
                return false;
            }
        }
    }
    // 保存表單標識
    $_SESSION['formSubmitCheck'][(time()+$iTimeOffset)] = $idForm;
    return true;
}


//paytype 付款方式 gid 團購id did 運費id usermymoney 使用余額支付
InitGP(array("action","paytype","num","gid","oid","did","usemymoney","fname","zip","tel","address","tmp","txtftitle","txtfidnum","txtfname","txtftel","txtfaddress","txtfps","orderdetail","receivetime","local")); //初始化變量全局返回
if (!empty($oid)) {
	include_once(INC_PATH."/order.class.php"); //包含團購類
	$o=new OrderClass();
	$ordervalue=$o->getone($oid);
	if (is_array($ordervalue)) {
		if ($ordervalue['money_state']==2) {
			showmessage("此訂單已付款！","-1",false);
		}
		$gid=$gid?$gid:$ordervalue['gid'];
		$num=$num?$num:$ordervalue['num'];
		$local=$local?$local:$ordervalue['local'];
		$did=$did?$did:$ordervalue['delivery'];
		$paytype=$paytype?$paytype:$ordervalue['delivery'];
		$usemymoney=$usemymoney?$usemymoney:0;
		$fname=$fname?$fname:$ordervalue['fname'];
		$address=$address?$address:$ordervalue['address'];
		$zip=$zip?$zip:$ordervalue['zip'];
		$tel=$tel?$tel:$ordervalue['tel'];
		$tmp=$tmp?$tmp:$ordervalue['tmp'];
		/* 自訂發票欄位 */
		$txtftitle=$txtftitle?$txtftitle:$ordervalue['txtftitle'];
		$txtfidnum=$txtfidnum?$txtfidnum:$ordervalue['txtfidnum'];
		$txtfname=$txtfname?$txtfname:$ordervalue['txtfname'];
		$txtftel=$txtftel?$txtftel:$ordervalue['txtftel'];
		$txtfaddress=$txtfaddress?$txtfaddress:$ordervalue['txtfaddress'];
		$txtfps=$txtfps?$txtfps:$ordervalue['txtfps'];
	}
	unset($ordervalue);
	unset($o);
}

if (!empty($gid) && !empty($num)){
    if (checkFormSubmit()===true){
    	//處理訂單到數據庫
    	//計算總價格
    	
    	include(INC_PATH."/group.class.php"); //包含團購類
		$gp=new GroupClass();
    	$groupvalue=$gp->getone($gid);
		if (!is_array($groupvalue)) {
			showmessage("團購id不存在","-1",false);
		}
		
    	include_once CFG_CACHEPATH.'/sys_pay.cache.php';//支付配置文件
	   	$payment_list = array();
		foreach($payment_select as $k => $val)
		{
			$temp_arr['name'] = $cfg_pay_info['name'][$k];
			$temp_arr['logo'] = 'images/pay/'.$cfg_pay_info['logo'][$k];
			$temp_arr['des']	= $cfg_pay_info['des'][$k];
			$temp_arr['value'] = $val;
			$temp_arr['exp'] = sprintf("%01.2f", $price*$payment_exp[$k]);
			$payment_list[$val] = $temp_arr;
		}
	
    	//商品類型是序列號
		
		//echo $groupvalue['gtypeid']."-". $groupvalue['freefreight'];
		
    	if($groupvalue['gtypeid']==0){
    		$priceCount=$groupvalue['shop_price']*$num;
    		$priceCount=sprintf("%01.2f",$priceCount);
    	//實物免運費商品	
    	}elseif ($groupvalue['gtypeid']==1 && $groupvalue['freefreight']==1)	{
    		$priceCount=$groupvalue['shop_price']*$num;
    		$priceCount=sprintf("%01.2f",$priceCount);
    		
    	//實物不免運費
    	}elseif ($groupvalue['gtypeid']==1){
	     	include(INC_PATH."/delivery.class.php");
			$dl=new DeliveryClass();
			$deliveryvalue=$dl->getdata(1,"did='{$did}'"); //獲取數據   
			
			//print_r($deliveryvalue);
			//echo "<br>[".$groupvalue['weight']."]";
			
			if ($groupvalue['weight'] <= $deliveryvalue['first_weight']) {
				$deliveryprice=$deliveryvalue['first_fee'];
			}elseif ($groupvalue['weight'] > $deliveryvalue['first_weight']){
				
/*				echo "delivervalue:".$deliveryvalue[0]['first_fee']."<br>";
				echo "groupvalue(weight):".$groupvalue['weight']."<br>";
				echo "num:".$num."<br>";
				echo "delivervalue:".$deliveryvalue[0]['first_weight']."]"."<br>";
				echo "[".$deliveryvalue[0]['continue_weight']."]"."<br>";
				echo "[".$deliveryvalue[0]['continue_fee']."]"."<br>";
*/				
				
				//原始運費計算方式
				//$deliveryprice=$deliveryvalue[0]['first_fee']+ceil((($groupvalue['weight']*$num- $deliveryvalue[0]['first_weight'])/$deliveryvalue[0]['continue_weight']))*$deliveryvalue[0]['continue_fee'];
				//新版運費計算方式
				if($num==1){
					$deliveryprice = 100;
				}else if($num==2){
					$deliveryprice = 100;
				}else if ($num >=3){
					$deliveryprice = 100;	
				}
			}
			

			
    		$priceCount=$groupvalue['shop_price']*$num+$deliveryprice;//計算總價格
    		$priceCount=sprintf("%01.2f",$priceCount);
    	}
    	
    	
		if($txtftitle !="" && $txtfidnum !=""){
			$formtitle='抬頭：'.$txtftitle.'<br />統編：'.$txtfidnum."<br />";
		}
		if($txtfname !=""){
			$forminfo="收件人：".$txtfname."<br />電話：".$txtftel."<br />地址：".$txtfaddress."<br />備註：".$txtfps;
		}
		
		//check gid
		if(isset($_SESSION['referid']) && (GetNum($gid)==$_SESSION['referid']))
			$refer = $_SESSION['refer'];
		else
			$refer = "buy917.com";
	
		unset($_SESSION['referid']);
		unset($_SESSION['refer']);
		unset($_SESSION['hostname']);
		
		
		
    	//整理數據插入訂單
    	$insertarray=array(
			"receivetime"=>GetNum($receivetime),
			"orderdetail"=>$orderdetail,
    		"gid"=>GetNum($gid),
    		"num"=>GetNum($num),
			"local"=>$local,
    		"order_total_price"=>$priceCount,
    		"uid"=>GetNum($_USERS['uid']),
    		"uname"=>$_USERS['uname'],
    		"payment"=>$paytype,
    		"payment_name"=>$payment_list[$paytype]['name'],
    		"delivery"=>$did,
    		"delivery_name"=>$deliveryvalue['name'],
    		"delivery_fee"=>$deliveryprice,
    		"order_weight"=>$groupvalue['weight']*$num,
    		"fname"=>$fname,
    		"address"=>$address,
    		"zip"=>$zip,
    		"tel"=>$tel,
    		"tmp"=>$tmp,
			"referer"=>$refer,
			//"tmp"=>$formtitle.$forminfo
    	);
		
		//echo "order detail:".$orderdetail;
		
    	include_once(INC_PATH."/order.class.php");
    	$o=new OrderClass();
    	
    	if (GetNum($oid)) {
    		$o->edit($oid,$insertarray);
    	}else {
    		$oid=$o->add($insertarray);
    	}
    	if (!is_numeric($oid)) {
    		showmessage("處理訂單出錯","-1",false,99999);
    	}else {
    		$value=$o->getone($oid);
    		//如果已付款存在 修改總價格
    		if ($value['order_incharge']!=0) {
    			$priceCount-=$value['order_incharge'];
    		}
    		
    	}    	
    	
    	//處理負數的商品價格！在用戶帳戶余額上加錢
		include(INC_PATH."/member.class.php");
		$m=new memberclass();
		
		//處理"活動"時使用0元 完成付款
		if($groupvalue['group_type']== 3){
			$o->edit_money_state($oid,2,$priceCount);
		}
		
		if($priceCount<0){
			$note="訂單：".$value["order_sn"]."付款";
			$m->moneyedit($_USERS['uname'],- $priceCount,$note);
			$o->edit_money_state($oid,2,$priceCount);
			$priceCount=0;
		}
		//是否使用賬戶余額是否全部或者部分
    	if ($usemymoney==1 and $_USERS['money'] > 0) {
    		//處理扣去用戶賬戶操作修改訂單狀態****未完待續
    		$note="訂單：".$value["order_sn"]."付款";
    		//用戶賬戶余額大於訂單總價格
    		if ($_USERS['money']>=$priceCount) {
    			$m->moneyedit($_USERS['uname'],- $priceCount,$note);
    			$o->edit_money_state($oid,2,$priceCount);
    			$priceCount=0;
    		}else{
    			$m->moneyedit($_USERS['uname'],- $_USERS['money'],$note);//賬戶余額減去
    			$o->edit_money_state($oid,1,$_USERS['money']);
    			$priceCount=$priceCount-$_USERS['money'];
    			
    		}
    		
    	}
    	
    	
    	
    	
    	
    	if ($priceCount==0) {
    		//提示購買成功跳轉到個人中心
    		showmessage("團購成功！","m.php",true,99999);
    	}
    	
    }else {
        showmessage("請不要重複提交表單！","",false,99999);
    }
    

}else {
	showmessage("缺少參數！","",false,99999);
}

$OrdersId=$value["order_sn"];//訂單號
$priceCount;//價格


//處理付款操作

require_once ROOT_PATH.'/paycenter/'.$paytype.'/config_pay_'.$paytype.'.php';//引用支付處理文件

include template('orderpay');//包含輸出指定模板
?>